﻿(function () {
    "use strict";

    /*DEBUG VARS*/
    var DEBUG = false;

    /*noAd Variable - True if Ad should not be displayed*/
    var noAd = true;

    //Get strings out of resources
    var recentPostsTitle = WinJS.Resources.getString('recentPostsTitle').value;
    var categoryTitle = WinJS.Resources.getString('categoryTitle').value;
    var offlineTitle = WinJS.Resources.getString('offlineTitle').value;
    var aboutTitle = WinJS.Resources.getString('aboutTitle').value;
    var url = WinJS.Resources.getString('wordpressURL').value;

    var urlRecentPost = url + "?json=get_recent_posts";
    var urlGetAllPost = url + "?json=get_recent_post";
    var urlGetCategories = url + "?json=get_category_index";
    var urlGetPostsBySlug = url + "?json=get_category_posts";
    var urlSearchPost = url + "?json=get_search_results";

    var cache = {};


    var folder = Windows.Storage.ApplicationData.current.localFolder;


    function log(str) {
        if (DEBUG && console && console.log) {
            console.log(str);
        }
    };
    
    function getCategories() {
        var options = {
            url: urlGetCategories
        };

        return doXhrRequest(options).then(function (e) {
            if (e !== null) {
                var categories = e.categories;

                var children = {};
                if (typeof categories == "undefined") {
                    return null;
                }
                for (var i = 0; i < categories.length; i++) {
                    if (categories[i].parent != 0) {
                        //category has a parent
                        for (var j = 0; j < categories.length; j++) {
                            //get parent
                            if (categories[j].id === categories[i].parent) {
                                categories[j].post_count += categories[i].post_count;
                            }
                        }
                    }
                }

                return categories;
            } else {
                return null;
            }

        });
    }

    function postAttributeHelper(postItem, key, slug) {

        var charCount_first_image = 135;
        var charCount_first = 416;
        var charCount_withoutImage = 200;
        var charCount_image = 58;
        var charCount = 116;
        var charCount_snapped_image = 50;
        var charCount_snapped = 65;
        if (postItem === null) {
            return null;
        }
        if (typeof postItem.excerpt !== "undefined" && postItem.excerpt !== null) {

            postItem.title = Helper.htmlSpecialChars(postItem.title, true);
            postItem.excerpt = Helper.htmlSpecialChars(postItem.excerpt, true);
            postItem.excerpt = postItem.excerpt.replace("[...]", "...");
            postItem.teaserContent = trimString(postItem.excerpt, charCount_image);
            postItem.teaserContentLong = trimString(postItem.excerpt, charCount_first_image);
            postItem.teaserContentWithoutImageLong = trimString(postItem.excerpt, charCount_first);
            postItem.teaserContentWithoutImage = trimString(postItem.excerpt, charCount_withoutImage);
            postItem.teaserContentSnapped = trimString(postItem.excerpt, charCount_snapped);
            postItem.teaserContentSnappedImage = trimString(postItem.excerpt, charCount_snapped_image);
        }

        postItem.teaserImage = postItem.thumbnail;
        postItem.teaserImageURL = "url(" + postItem.thumbnail + ")";
        postItem.teaserDate = getTeaserDate(postItem.date);





        if (typeof postItem.categories[0] !== "undefined") {
            postItem.catTitle = postItem.categories[0].title;
        } else {
            console.log("asfd");
        }


        if (typeof slug !== "undefined") {
            postItem.colorBarClass = slug + " default";
        } else {

            if (typeof postItem.categories[0] !== "undefined") {
                postItem.colorBarClass = postItem.categories[0].slug + " default";
            }
        }
        if (typeof key !== "undefined") {
            postItem.key = key;
        } else {

            if (typeof postItem.categories[0] !== "undefined") {
                postItem.key = postItem.categories[0].slug;
            }
        }
        return postItem;
    }

    function getRecentPosts(count, getAd) {

        // check if count is set
        if (typeof count !== "undefined") {
            var countURL = "&count=" + count;
            urlRecentPost += countURL;
        }
        var options = {
            url: urlRecentPost
        };

        return doXhrRequest(options).then(function (e) {
            if (typeof e !== "undefined" && e !== null) {
                var count = e.count;
                var count_total = e.count_total;

                for (var j = 0; j < e.posts.length; j++) {
                    e.posts[j] = postAttributeHelper(e.posts[j], recentPostsTitle);
                }
                //return e.posts;
                var result = [];
                if ((typeof getAd === "undefined" || getAd === false) || noAd) {
                    
                    return e.posts;
                } else {

                    for (var i = 0; i < e.posts.length; i++) {

                        if (count != 100) {
                            if (i == 4) {
                                var ad = {
                                    key: recentPostsTitle,
                                    ad: true
                                };
                                result.push(ad);
                            }
                        }

                        if (i % 20 === 0 && i != 0) {
                            var ad = {
                                key: recentPostsTitle,
                                ad: true
                            };
                            result.push(ad);
                        }
                        result.push(e.posts[i]);
                    }
                    return result;
                }


            } else {
                return null;
            }

        });
    }

    function doXhrRequest(options) {
        var timestamp = Number(new Date()); // current time as number
        options.url = options.url + "&nocache=" + timestamp;

        return WinJS.xhr(options).then(
            function (xmlHttpRequest) {
                log("success");
                log(xmlHttpRequest.responseText);
                //TODO Try catch - error handling
                try {
                    var data = JSON.parse(xmlHttpRequest.responseText);
                    return data;
                }
                catch (parseException) {
                    return null;
                }
            },
            function (xmlHttpRequest) {
                log("fail");
                return null;
            },
            function (xmlHttpRequest) {
                log("progress");
            }
        );
    }

    function getCategoryByTitle(term) {
        return getCategories().then(function (list) {
            if (list == null) {
                return null;
            }

            for (var i = 0; i < list.length; i++) {
                if (list[i].title == term) {
                    return list[i];
                }
            }

        });
    }

    function getPostsByCategorySlug(catObject, count, getAd) {

        // check if count is set
        if (typeof count !== "undefined" && count !== null) {
            var countURL = "&count=" + count;
            urlGetPostsBySlug += countURL;
        }

        var catSlugURL = "&id=" + catObject.id;

        var options = {
            url: urlGetPostsBySlug + catSlugURL
        };

        log(options.url);

        return doXhrRequest(options).then(function (e) {
            if (typeof e !== "undefined" && e !== null) {

                for (var j = 0; j < e.posts.length; j++) {
                    e.posts[j] = postAttributeHelper(e.posts[j], catObject.slug, catObject.slug);
                }

                var promises = [];
                var pagesCount = e.pages;
                var posts = [];
                for (var i = 0; i < e.posts.length; i++) {
                    posts.push(e.posts[i]);
                }

                var re = {
                    count: pagesCount,
                    posts: posts,
                    url: options.url
                };

                return re;


            } else {
                return null;
            }
        }).then(function (res) {
            if (res !== null) {
                var pagesCount = res.count;
                var allCatPosts = [];

                for (var i = 0; i < res.posts.length; i++) {
                    allCatPosts.push(res.posts[i]);
                }

                var promises = [];
                for (var k = 2; k < pagesCount + 1; k++) {
                    var pageURL = res.url + "&page=" + k;
                    var p = doXhrRequest({ url: pageURL });
                    promises.push(p);
                }

                return WinJS.Promise.join(promises).then(function (list) {

                    for (var l = 0; l < list.length; l++) {
                        var e = list[l];
                        if (e !== null) {


                            for (var j = 0; j < e.posts.length; j++) {
                                if (typeof e.posts[j].categories[0] !== "undefined") {
                                    e.posts[j] = postAttributeHelper(e.posts[j], catObject.slug, catObject.slug);
                                    allCatPosts.push(e.posts[j]);
                                }
                            }
                        }
                    }

                    //advertising
                    if ((typeof getAd === "undefined" || getAd !== true) || noAd) {
                        return allCatPosts;
                    } else {
                        var result = [];
                        for (var i = 0; i < allCatPosts.length; i++) {
                            if (i % 20 === 0 && i !== 0) {
                                var ad = {
                                    key: recentPostsTitle,
                                    ad: true
                                };
                                result.push(ad);
                            }
                            result.push(allCatPosts[i]);
                        }
                        return result;
                    }
                });
            }
        });
    }

    function getPostsByCategoryCatItem(catObject, count, getAd) {

        // check if count is set
        if (typeof count !== "undefined") {
            var countURL = "&count=" + count;
            urlGetPostsBySlug += countURL;
        }

        var catSlugURL = "&id=" + catObject.id;

        var options = {
            url: urlGetPostsBySlug + catSlugURL
        };

        return doXhrRequest(options).then(function (e) {
            if (typeof e !== "undefined" && e !== null) {
                for (var j = 0; j < e.posts.length; j++) {
                    e.posts[j] = postAttributeHelper(e.posts[j], catObject.slug, catObject.slug);
                }

                if ((typeof getAd === "undefined" || getAd !== true) || noAd) {
                    return e.posts;
                } else {
                    var result = [];
                    for (var i = 0; i < e.posts.length; i++) {
                        if (i % 20 === 0 && i !== 0) {
                            var ad = {
                                key: recentPostsTitle,
                                ad: true
                            };
                            result.push(ad);
                        }
                        result.push(e.posts[i]);
                    }
                    return result;
                }

            } else {
                return null;
            }
        });
    }

    function getAllRecentPosts(count, getAd) {

        var options = {
            url: urlGetAllPost
        };

        return doXhrRequest(options).then(function (e) {
            if (typeof e !== "undefined" && e !== null) {

                console.log("recent total: " + e.count_total);


                for (var j = 0; j < e.posts.length; j++) {
                    e.posts[j] = postAttributeHelper(e.posts[j], recentPostsTitle);
                }

                var promises = [];
                var pagesCount = e.pages;
                var posts = [];
                for (var i = 0; i < e.posts.length; i++) {
                    posts.push(e.posts[i]);
                }

                var re = {
                    count: pagesCount,
                    posts: posts,
                    url: options.url
                };

                return re;


            }
        }).then(function (res) {
            if (res !== null && typeof res !== "undefined") {
                var pagesCount = res.count;
                var allCatPosts = [];

                for (var i = 0; i < res.posts.length; i++) {
                    allCatPosts.push(res.posts[i]);
                }

                var promises = [];
                for (var k = 2; k < pagesCount + 1; k++) {
                    var pageURL = res.url + "&page=" + k;
                    console.log("recent promise: " + pageURL);
                    var p = doXhrRequest({ url: pageURL });
                    promises.push(p);
                }

                return WinJS.Promise.join(promises).then(function (list) {

                    for (var l = 0; l < list.length; l++) {
                        var e = list[l];
                        if (e !== null) {


                            for (var j = 0; j < e.posts.length; j++) {
                                if (typeof e.posts[j].categories[0] !== "undefined") {
                                    e.posts[j] = postAttributeHelper(e.posts[j]);
                                    allCatPosts.push(e.posts[j]);
                                }
                            }
                        }
                    }

                    console.log("recent length: " + allCatPosts.length);

                    //advertising
                    if ((typeof getAd === "undefined" || getAd !== true) || noAd) {
                        return allCatPosts;
                    } else {
                        var result = [];
                        for (var i = 0; i < allCatPosts.length; i++) {
                            if (i % 20 === 0 && i !== 0) {
                                var ad = {
                                    key: recentPostsTitle,
                                    ad: true
                                };
                                result.push(ad);
                            }
                            result.push(allCatPosts[i]);
                        }
                        return result;
                    }
                });
            }
        });


    }

    function resetCache() {
        //cache = {};
        cache['getRecentPosts'] = undefined;
    }

    function unifyItemsForListLayout() {

        var promises = [];
        var items = [];

        //save promise "getCategories" in a array
        //save category-items in the items array
        //add to each item the key "Kategorie"
        if (typeof cache['getCategories'] !== "undefined") {

            var c = cache['getCategories'];
            if (c !== null) {
                for (var i = 0; i < c.length; i++) {
                    c[i].key = categoryTitle;
                    c[i].teaserImage = false;
                    c[i].firstParagraph = false;
                    items.push(c[i]);
                }
            }
        } else {
            promises[0] = getCategories().then(function (c) {
                if (c !== null) {
                    for (var i = 0; i < c.length; i++) {
                        c[i].key = categoryTitle;
                        c[i].teaserImage = false;
                        c[i].firstParagraph = false;
                        items.push(c[i]);
                    }
                    cache['getCategories'] = c;
                }

            });
        }


        promises[1] = loadData(6, true).then(function (e) {
            if (typeof e !== "undefined") {
                for (var k = 0; k < e.length; k++) {
                    //e[k].key = offlineTitle;
                    ////e[k].teaserImage = getFirstImage(e[k].content);
                    //e[k].teaserImage = e[k].thumbnail;
                    //e[k].teaserContent = getTeaserContent(e[k].content, e[k].teaserImage);
                    //e[k].teaserContentLong = getTeaserContent(e[k].content, e[k].teaserImage,true);
                    //e[k].teaserDate = getTeaserDate(e[k].date);
                    //e[k].colorBarClass = e[k].categories[0].slug;
                    items.push(e[k]);
                }
                //var ad = {
                //    key: offlineTitle,
                //    ad: true
                //};
                //items.push(ad);
            }
        });

        //save promise "getRecentPosts" in a array
        //save recentPost-items in the items array
        //add to each item the key "Posts"
        if (typeof cache['getRecentPosts'] !== "undefined") {
            //if (false) {

            var d = cache['getRecentPosts'];
            if (d !== null) {
                for (var j = 0; j < d.length; j++) {

                    items.push(d[j]);
                }
            }
        } else {
            promises[2] = getRecentPosts(7, true).then(function (d) {
                if (d !== null) {
                    for (var j = 0; j < d.length; j++) {

                        items.push(d[j]);
                    }
                    cache['getRecentPosts'] = d;
                }
                //var ad = {
                //    key: recentPostsTitle,
                //    ad: true
                //};
                //items.push(ad);
            });
        }

        //join promises and display all items (categories & recentPosts)
        return WinJS.Promise.join(promises).then(function () {

            for (var j = 0; j < 2; j++) {
                var aboutItem = getAboutItem();
                if (j === 0) {
                    aboutItem.class = "info";
                    aboutItem.colorBarClass = "default";
                } else {
                    aboutItem.class = "team";
                    aboutItem.teamkey = "team" + j;
                    aboutItem.colorBarClass = "default";
                    //aboutItem.colorBarClass = "default";
                }
                items.push(aboutItem);
                //res.push(aboutItem);
            }
            return items;
        });
    }

    function getGroupedList(list) {

        // Function used to sort the groups
        function compareGroups(left, right) {

            function checkGroup(cat) {
                if (cat === categoryTitle) {
                    return 3;
                } else if (cat === recentPostsTitle) {
                    return 1;
                } else if (cat === offlineTitle) {
                    return 2;
                } else if (cat === aboutTitle) {
                    return 4;
                } else {
                    return 5;
                }
            }

            return checkGroup(left) - checkGroup(right);
        }

        // Function which returns the group key that an item belongs to
        function getGroupKey(dataItem) {
            if (dataItem == null) {
                return null;
            }
            return dataItem.key;
        }

        // Function which returns the data for a group
        function getGroupData(dataItem) {
            if (dataItem == null) {
                return null;
            }
            return {
                title: dataItem.key
            };
        }

        var mylist = new WinJS.Binding.List();

        for (var i = 0; i < list.length; i++) {
            mylist.push(list[i]);
        }

        // Create a grouped list for the ListView from the item data and the grouping functions
        var myGroupedList = mylist.createGrouped(getGroupKey, getGroupData, compareGroups);

        return myGroupedList;
    }

    function getGroupedSearch(list) {

        // Function used to sort the groups
        function compareGroups(a, b) {
            if (typeof a !== "undefined" || typeof b !== "undefined") {
                return 0;
            }
            var A = a.toLowerCase();
            var B = b.toLowerCase();
            if (A < B) {
                return -1;
            } else if (A > B) {
                return 1;
            } else {
                return 0;
            }
        }

        // Function which returns the group key that an item belongs to
        function getGroupKey(dataItem) {
            console.log(dataItem.key);
            return dataItem.catTitle;
        }

        // Function which returns the data for a group
        function getGroupData(dataItem) {
            var fullTitle = dataItem.categories[0].title;
            return {
                title: dataItem.key,
                titleReal: fullTitle
            };
        }

        var mylist = new WinJS.Binding.List();

        if (list === null || typeof list == "undefined" || list.length == 0) {
            // Create a grouped list for the ListView from the item data and the grouping functions
            var myGroupedList = mylist.createGrouped(getGroupKey, getGroupData);

            var result = {
                list: myGroupedList,
                empty: true
            };
            return result;
        }

        for (var i = 0; i < list.length; i++) {
            mylist.push(list[i]);
            //console.log(list[i].)
        }
        // Create a grouped list for the ListView from the item data and the grouping functions
        var myGroupedList = mylist.createGrouped(getGroupKey, getGroupData, compareGroups);

        var result = {
            list: myGroupedList,
            empty: false
        };
        return result;
    }

    function saveToOfflineList(items, remove) {

        //check if there are stored posts
        return loadData().then(function (d) {
            if (d.length > 0) {
                if (remove !== true) {
                    for (var i = 0; i < d.length; i++) {
                        items.push(d[i]);
                    }
                }
            }
        }).then(function () {
            var output = '[]';
            if (items.length > 0) {
                output = JSON.stringify(items);
            }

            return folder.createFileAsync("offlinePosts.json", Windows.Storage.CreationCollisionOption.replaceExisting).then(function (file) {
                return Windows.Storage.FileIO.appendTextAsync(file, output);
            }).done(function () {

            });
        });

    }

    function checkIfSaved(post) {
        return loadData().then(function (list) {
            for (var i = 0; i < list.length; i++) {
                if (list[i].id == post.id) {
                    return true;
                }
            }
            return false;
        });
    }

    function loadData(count, getAd) {

        return new WinJS.Promise(function (complete, error) {
            WinJS.Application.local.exists("offlinePosts.json").then(function (e) {
                if (e === true) {
                    folder.getFileAsync("offlinePosts.json")
                    .then(function (file) {
                        return Windows.Storage.FileIO.readTextAsync(file);
                    })
                    .then(function (content) {
                        try {
                            content = eval(content);
                        } catch (e) {
                            complete([]);
                        }
                        if (typeof content === "undefined") {
                            content = [];
                        }
                        for (var j = 0; j < content.length; j++) {
                            content[j] = postAttributeHelper(content[j], offlineTitle);
                        }
                        if (typeof count !== "undefined" && count !== null) {
                            var sizedArray = [];
                            for (var i = 0; i < content.length && i < count; i++) {
                                sizedArray.push(content[i]);
                            }
                            var result = [];

                            if ((typeof getAd === "undefined" || getAd !== true) || noAd) {
                                complete(sizedArray);
                            } else {
                                for (var i = 0; i < sizedArray.length; i++) {
                                    if (i % 4 === 0 && i !== 0) {
                                        var ad = {
                                            key: offlineTitle,
                                            ad: true
                                        };
                                        result.push(ad);
                                    }
                                    result.push(sizedArray[i]);
                                }
                                complete(result);
                            }

                        } else {
                            complete(content);
                        }
                    });
                } else {
                    complete([]);
                }
            })

        });
    }

    function saveObjectToFile(name, obj) {
        var x = JSON.stringify(obj);
        return folder.createFileAsync(name + ".txt", Windows.Storage.CreationCollisionOption.replaceExisting).then(function (file) {
            return Windows.Storage.FileIO.appendTextAsync(file, x);
        }).done(function () {

        });
    }
    function loadObjectFromFile(name) {
        /// <summary>
        /// load json-formated posts form file
        /// note: each json is in a single row
        /// </summary>
        /// <param name="count">max count of items to be returned</param>
        // check if count is set

        return new WinJS.Promise(function (complete, error) {
            WinJS.Application.local.exists(name + ".txt").then(function (e) {
                if (e === true) {
                    folder.getFileAsync(name + ".txt")
                    .then(function (file) {
                        return Windows.Storage.FileIO.readTextAsync(file);
                    })
                    .then(function (content) {
                        try {
                            content = eval(content);
                        } catch (e) {
                            complete(null);
                        }
                        complete(content);
                    });
                } else {
                    complete(null);
                }
            })

        });
    }


    function deletePosts(listOfPostsId) {

        return new WinJS.Promise(function (complete, error) {
            WinJS.Application.local.exists("offlinePosts.json").then(function (e) {
                if (e === true) {
                    folder.getFileAsync("offlinePosts.json")
                    .then(function (file) {
                        return Windows.Storage.FileIO.readTextAsync(file);
                    })
                    .then(function (d) {
                        var d = eval(d);
                        //iterate through stored posts
                        for (var p = 0; p < d.length; p++) {

                            //iterate through post to be delteted
                            for (var i = 0; i < listOfPostsId.length; i++) {

                                //check if stored post contains in the to-be-delted list
                                if (listOfPostsId[i] === d[p].id) {
                                    //delete item
                                    log("kill");
                                    d.splice(d.indexOf(d[p]), 1);
                                }
                            }
                        }
                        saveToOfflineList(d, true);
                    });
                } else {
                    complete([]);
                }
            })
        });
    }

    function deleteLocalSavedData() {

        var localFolder = WinJS.Application.local;
        localFolder.exists("offlinePosts.json").then(function (e) {
            if (e === true) {
                localFolder.remove("offlinePosts.json").done(function (p) {
                    log("offlinePost.json removed");
                    return true;
                })
            }
        });

    }

    function trimString(string, size) {

        if (typeof string !== "undefined") {
            if (string.length > size) {
                var trimedString = string.substring(0, size - 3);
                trimedString += '...';
                return trimedString;
            }
            return string;
        } else {
            return "";
        }
    }

    function getTeaserDate(dateInfo) {

        if (typeof dateInfo !== "undefined") {
            var fullDate = dateInfo.split(' ')[0];
            var date = fullDate.split('-')[2];
            var month = fullDate.split('-')[1] - 1;
            var year = fullDate.split('-')[0];

            var today = new Date();
            log("Today is: " + today.toLocaleDateString());

            var yesterday = new Date(today.getTime() - (24 * 60 * 60 * 1000));
            var twoDaysAgo = new Date(yesterday.getTime() - (24 * 60 * 60 * 1000));
            var threeDaysAgo = new Date(twoDaysAgo.getTime() - (24 * 60 * 60 * 1000));
            var dateObject = new Date(year, month, date);

            //resource strings
            var gridPostToday = WinJS.Resources.getString('gridPostToday').value;
            var gridPostYesterday = WinJS.Resources.getString('gridPostYesterday').value;
            var gridPost2DaysAgo = WinJS.Resources.getString('gridPost2DaysAgo').value;
            var gridPost3DaysAgo = WinJS.Resources.getString('gridPost3DaysAgo').value;

            if (today.toLocaleDateString() === dateObject.toLocaleDateString()) {
                return gridPostToday;
            } else if (yesterday.toLocaleDateString() === dateObject.toLocaleDateString()) {
                return gridPostYesterday;
            } else if (twoDaysAgo.toLocaleDateString() === dateObject.toLocaleDateString()) {
                return gridPost2DaysAgo;
            } else if (threeDaysAgo.toLocaleDateString() === dateObject.toLocaleDateString()) {
                return gridPost3DaysAgo;
            } else {
                return dateObject.toLocaleDateString();
            }
        }

    }

    function getAboutItem() {

        var about = {
            key: aboutTitle
        }
        return about;
    }

    function searchPost(query, count, getAd) {

        // check if count is set
        if (typeof count !== "undefined" && count !== null) {
            var countURL = "&count=" + count;
            urlSearchPost += countURL;
        }

        var searchURL = "&search=" + query;

        var options = {
            url: urlSearchPost + searchURL
        };

        log(options.url);

        return doXhrRequest(options).then(function (e) {
            if (typeof e !== "undefined" && e !== null) {

                if (e.status == "error") {
                    return null;
                }

                log("total: " + e.count_total);


                for (var j = 0; j < e.posts.length; j++) {
                    e.posts[j] = postAttributeHelper(e.posts[j]);
                }

                var promises = [];
                var pagesCount = e.pages;
                var posts = [];
                for (var i = 0; i < e.posts.length; i++) {
                    posts.push(e.posts[i]);
                }

                var re = {
                    count: pagesCount,
                    posts: posts,
                    url: options.url
                };

                return re;


            } else {
                return null;
            }
        }).then(function (res) {
            if (res !== null) {
                var pagesCount = res.count;
                var allCatPosts = [];

                for (var i = 0; i < res.posts.length; i++) {
                    allCatPosts.push(res.posts[i]);
                }

                var promises = [];
                for (var k = 2; k < pagesCount + 1; k++) {
                    var pageURL = res.url + "&page=" + k;
                    log("recent promise: " + pageURL);
                    var p = doXhrRequest({ url: pageURL });
                    promises.push(p);
                }

                return WinJS.Promise.join(promises).then(function (list) {

                    for (var l = 0; l < list.length; l++) {
                        var e = list[l];
                        if (e !== null) {


                            for (var j = 0; j < e.posts.length; j++) {
                                //check if post has a category
                                if (typeof e.posts[j].categories[0] !== "undefined") {
                                    e.posts[j] = postAttributeHelper(e.posts[j]);
                                    allCatPosts.push(e.posts[j]);
                                }
                            }
                        } else {
                            //return null;
                        }
                    }

                    log("recent length: " + allCatPosts.length);

                    //advertising
                    if ((typeof getAd === "undefined" || getAd !== true) || noAd) {
                        return allCatPosts;
                    } else {
                        var result = [];
                        for (var i = 0; i < allCatPosts.length; i++) {
                            if (i % 4 === 0 && i !== 0) {
                                var ad = {
                                    key: recentPostsTitle,
                                    ad: true
                                };
                                result.push(ad);
                            }
                            result.push(allCatPosts[i]);
                        }
                        return result;
                    }
                });
            }
        });
    }

    function searchPostList(res) {

        return getCategories().then(function (cats) {
            if (res !== null && cats !== null) {
                var filtered = {};

                for (var i = 0; i < cats.length; i++) {

                    var catPosts = [];

                    for (var j = 0; j < res.length; j++) {

                        if (res[j].categories[0].slug == cats[i].slug) {
                            catPosts.push(res[j]);
                        }
                    }
                    filtered[cats[i].title] = catPosts;
                }

                return filtered;
            } else {
                return null;
            }

        });
    }

    function getPostByURL(url) {
        var urlPreParam = "?"
        if (url.indexOf("?") !== -1) {
            urlPreParam = "&";
        }
        return doXhrRequest({ url: url + urlPreParam + "json=1" }).then(function (e) {
            if (e !== null) {
                return e.post;
            } else {
                return null;
            }
        });
    }

    WinJS.Namespace.define("Data", {
        getGroupedList: getGroupedList,
        getCategories: getCategories,
        getRecentPosts: getRecentPosts,
        getPostsByCategorySlug: getPostsByCategorySlug,
        saveToOfflineList: saveToOfflineList,
        loadData: loadData,
        deletePosts: deletePosts,
        deleteLocalSavedData: deleteLocalSavedData,
        getAboutItem: getAboutItem,
        getAllRecentPosts: getAllRecentPosts,
        checkIfSaved: checkIfSaved,
        getPostsByCategoryCatItem: getPostsByCategoryCatItem,
        unifyItemsForListLayout: unifyItemsForListLayout,
        getGroupedSearch: getGroupedSearch,
        searchPostList: searchPostList,
        getCategoryByTitle: getCategoryByTitle,
        loadObjectFromFile: loadObjectFromFile,
        saveObjectToFile: saveObjectToFile,
        searchPost: searchPost,
        getPostByURL: getPostByURL,
        resetCache: resetCache
    });

})();
